# -*- encoding: utf-8 -*-
# 
# Lúcuma
# Copyright © 2008 Diego Escalante Urrelo  <diegoe@gnome.org>
# 
# Licensed under the GNU General Public License Version 2
# 
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
# 
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor
# Boston, MA  02110-1301, USA.
# 

from lucuma.personas.models import Persona, MetaPersona
from django.http import HttpResponseRedirect
from django.shortcuts import render_to_response

def __do_login(request):
    """
    Does the actual login, returns True if the user+passwd is ok, otherwise
    returns False.
    """
    user = request.POST.get('login_user', None)
    passwd = request.POST.get('login_passwd', None)

    persona = Persona.objects.filter(user__exact=user)
    
    if (len(persona) > 0) and persona[0].passwd == passwd:
        persona = persona[0]
        request.session['logged'] = True
        request.session['persona_id'] = persona.id
        request.session['whoami'] = {}
        
        if persona.meta:
            request.session['whoami']['name'] = persona.meta.name
            request.session['whoami']['lastname'] = persona.meta.lastname
        else:
            request.session['whoami']['name'] = persona.user
            request.session['whoami']['lastname'] = None
        
        return True
    else:
        return False

def login(request):
    #FIXME: Remove this method?
    """
    Standard login, with the usual redirects. Not in use now.
    """
    if __do_login(request):
        return HttpResponseRedirect('/')
    else:
        return HttpResponseRedirect('/login') 

def login_ajax(request):
    #FIXME: Make sure wrong logins return the correct template.
    """
    Does the AJAX login, it returns a rendered profile if successful or a login
    form otherwise.
    """
    from lucuma.personas.templatetags.personas_tags import persona_profile, persona_login

    context = {'session': request.session}

    if __do_login(request):
        persona_dict = persona_profile(context)
        return render_to_response('persona_profile.html', 
            persona_dict)
    else:
        persona_dict = persona_login(context)
        return render_to_response('persona_login.html', 
            persona_dict)

def logout(request):
    """
    Remove the session info for this Persona and then Redirect to the /.
    """
    try:
        del request.session['logged']
        del request.session['persona_id']
        del request.session['whoami']
    except KeyError:
        pass
    
    # FIXME: Safe?
    return HttpResponseRedirect('/')

def add(request):
    """
    Add a new Person.
    """
    persona = Persona()
    persona.user = request.POST.get('personas_add_user')
    persona.passwd = request.POST.get('personas_add_passwd')

    meta = MetaPersona()
    meta.name = request.POST.get('personas_add_name')
    meta.lastname = request.POST.get('personas_add_lastname')
    meta.email = request.POST.get('personas_add_email')
    #FIXME: We have to resize the photo and create a thumbnail (or just
    # resize).
    photo = request.FILES.get('personas_add_photo')

    if photo:
        meta.save_photo_file(photo['filename'], photo['content'])

    meta.save()

    persona.meta = meta
    persona.save()

    return HttpResponseRedirect('/')
